import { Space, Card, Button, Form, Popconfirm, message } from 'antd';
import { useEffect, useState, createContext } from 'react';
import { listApi, removeApi, addApi } from '@/utils/api';
import { formatTime2 } from '../utils/index';
import moment from 'moment';
import Search from './components/Search';
import Modal from './components/Modal';
import Table from './components/Table';

export const context = createContext({});
const { Provider } = context;

interface Itemtype {
  birthday: number;
  city: string;
  name: string;
  sex: string;
  _id: string;
}

const cancel = () => {
  console.log('no');
};

const Index = () => {
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [dataSource, setDataSource] = useState<Itemtype[]>([]);
  const [current, setCurrent] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const [searchObj, setSearchObj] = useState({});
  const [visible, setVisible] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('新增学员');

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render(text: string) {
        return text === '1' ? '男' : '女';
      },
    },
    {
      title: '城市',
      dataIndex: 'city',
    },
    {
      title: '出生日期',
      dataIndex: 'birthday',
      render(text: number) {
        return formatTime2(text);
      },
    },
    {
      title: '操作',
      render(text: string, record: Itemtype) {
        return (
          <Space>
            <Button onClick={() => editOpen(record)}>编辑</Button>
            <Popconfirm
              title={`你确定要删除${record.name}吗?`}
              onConfirm={confirm(record)}
              onCancel={cancel}
              okText="Yes"
              cancelText="No"
            >
              <Button danger type="primary">
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const getData = async () => {
    const res = await listApi({
      page_size: 10,
      current_page: current,
      ...searchObj,
    });
    const result = res.result.map((item: Itemtype) => {
      return { ...item, key: item._id };
    });
    setDataSource(result);
    setTotal(res.count);
  };

  useEffect(() => {
    getData();
  }, [current, searchObj]);

  const onFinish = (values: any) => {
    setCurrent(1);
    setSearchObj(values);
  };

  const reset = () => {
    form.resetFields();
    setSearchObj({});
  };

  const paginationChange = (page: number, pageSize: number) => {
    setCurrent(page);
  };

  const confirm = (record: Itemtype) => async () => {
    const res = await removeApi({ id: record._id });
    if (res.status === 0) {
      message.success(res.msg);
      getData();
    }
  };

  const open = () => {
    setTitle('新增学员');
    form2.resetFields();
    setVisible(true);
  };

  const editOpen = (record: Itemtype) => {
    setTitle('编辑学员');
    setVisible(true);
    form2.setFieldsValue({
      name: record.name,
      sex: record.sex,
      city: record.city,
      birthday: moment(formatTime2(record.birthday), 'YYYY-MM-DD'),
    });
  };

  const handleOk = () => {
    form2
      .validateFields()
      .then(async (values) => {
        const res = await addApi({
          ...values,
          birthday: new Date(values.birthday).getTime(),
        });
        if (res.status === 0) {
          setVisible(false);
          message.success(res.msg);
          getData();
        }
      })
      .catch((errorInfo) => {
        return errorInfo;
      });
  };

  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <Provider
      value={{
        dataSource,
        columns,
        current,
        total,
        paginationChange,
      }}
    >
      <Space direction="vertical" style={{ display: 'flex' }}>
        <Card>
          <Search form={form} onFinish={onFinish} reset={reset} />
        </Card>
        <Card title="学生管理" extra={<Button onClick={open}>新增</Button>}>
          <Table />
        </Card>

        <Modal
          title={title}
          visible={visible}
          handleOk={handleOk}
          handleCancel={handleCancel}
          form2={form2}
        />
      </Space>
    </Provider>
  );
};

export default Index;
